import socket
import threading
import time
from tkinter.messagebox import *

class SendServer:
    def __init__(self, username):
        self.username = username
        self.conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            self.conn.connect(("127.0.0.1", 7890))
            print("TCP服务器连接成功")
        except ConnectionError:
            print("服务器没有启动")

    def check_online(self):
        ls_box = str([str(self.username), "root", "在线"]).encode("utf-8")
        # ls_box = """["15133854715", "root", "在线"]""".encode("utf-8")
        print(ls_box)
        while True:
            try:
                self.conn.send(ls_box)
                time.sleep(1)
            except :
                print("服务器失联")
                # showinfo("","无法连接TCP服务器")
                return 0


    def rec_messages(self):
        return self.conn.recv(1024).decode("utf-8")

        # try:
        # # 接受TCP客户端发来的信息
        #     return self.conn.recv(1024).decode("utf-8")
        # except OSError:
        #     print("服务器断链")
        #     return None
        # while True:
        #     rec_mes = self.conn.recv(1024)
        #     print(rec_mes.decode("utf-8"))

    def send_one_message(self, messages):
        self.conn.send(messages)
    # 关闭连接
    def close1(self):
        self.conn.close()


if __name__ == '__main__':
    pass
    # 测试函数
    # c1 = SendServer()
    # threading_check = threading.Thread(target=c1.check_online)
    # threading_check.start()
    # print("1")
    # time.sleep(5)
    # print("开始发送")
    # ls_message = """["我是谁","发送睡","我发啥"]""".encode("utf-8")
    # c1.send_one_message(ls_message)
    # print("发送结束")
